import React, { useState, useEffect } from 'react';
import Breadcrumb, { Item } from '../../../components/Breadcrumb';
import Form from '@knownsec/react-component/dist/Form';
import Dialog from '@knownsec/react-component/dist/Dialog';
import Button from '@knownsec/react-component/dist/Button';
import Tooltip from '@knownsec/react-component/dist/Tooltip';
import Confirm from '@knownsec/react-component/dist/Confirm';
import { EyeOutlined } from '@ant-design/icons';
import { Dropdown } from 'antd';
import Icon from '@knownsec/react-component/dist/Icon';
import Message from '@knownsec/react-component/dist/Message';
import { GetQueryString } from '../../../helpers/getUrlParams';
import moment from 'moment';
import s from '../style.module.css';
import cn from 'classnames';
import fetchFer from 'API/fetch';
import _, { cloneDeep } from 'lodash';
import { CheckmarkOutline32 as Success9 } from '@carbon/icons-react';
import pathOr from 'ramda/es/pathOr';
import ms from 'ms';
import formatSubmitData from './formatSubmitData';
import { getTaskEnable, isSslEnable } from './unit';
import { getResD } from '../../../index';
import {
	SSL_CATEGORY_KEY_LABEL_MAP,
	CONTENT_KEYWORD_TYPES,
	CONTENT_PRIVACY_DISCLOSURE_TYPES,
	FREQUENCY_UNIT_MAP,
	WARNING_CATEGORY_KEY_LABEL_MAP,
} from '../../../../common/constants';
import WebStep1 from './webStep1';
import WebStep2 from './webStep2';
const SECURITY_EVENT_TYPE_MAP = {
	black_links: '暗链',
	broken_links: '坏链',
	cryjack: '挖矿',
	malscan: '挂马',
	foreign_links_2: '风险外链(违规内容)',
	foreign_links_3: '风险外链(风险域名)',
	foreign_links_1: '风险外链(未备案)',
};

const ASSET_TASK_TYPE_MAP = {
	web: 'Web安全监测',
	host: '主机安全监测',
	aviliable: '可用性监测',
};

// 仅包含web和主机监测新增修改任务
const defaultWebData = {
	name: '',
	job_ids: [],
	type: 1,
	interval: 604800000,
	trigger_type: 'schedule',
	vul_settings: {
		interval: 604800000,
		vulType: 'all',
		enableSitePortraitTriggerMonitor: false,
		enable: true,
		collect: {
			type: 'full',
			depth: [3],
			maxPage: [1000],
			speed: ['medium'],
			vulns: [],
			vul: ['1'],
		},
	},
	ssl_settings: {
		interval: 86400000,
		enable: true,
		sslType: 'all',
		collect: {
			pluginCategories: Object.keys(SSL_CATEGORY_KEY_LABEL_MAP),
		},
	},
	content_settings: {
		type: 'full',
		interval: 86400000,
		enable: true,
		collect: {
			includeUrl: '/',
			depth: [3],
			maxPage: [1000],
			plugins: ['keyword', 'privacy_disclosure'],
			privacyDisclosureStatus: true,
			privacyDisclosureTypes: CONTENT_PRIVACY_DISCLOSURE_TYPES.reduce(
				(t, i) => {
					t.push(i.idx);
					return t;
				},
				[]
			),
			systemKeywordStatus: true,
			systemKeywordTypes: CONTENT_KEYWORD_TYPES.reduce((t, i) => {
				t.push(i.idx);
				return t;
			}, []),
		},
	},
	change_check_settings: {
		interval: 86400000,
		enable: true,
		collect: {
			depth: [3],
			maxPage: [100],
			enableBaseChange: true,
			baseChangeCount: [5],
			keywords: '',
			resources: '',
			changeType: Object.keys(WARNING_CATEGORY_KEY_LABEL_MAP.changeCheck),
			type: 'full',
			includeUrl: '',
			excludeUrl: '',
		},
	},
	security_event_settings: {
		interval: 86400000,
		enable: true,
		collect: {
			depth: [3],
			maxPage: [1000],
			plugins: Object.keys(SECURITY_EVENT_TYPE_MAP),
		},
	},
	hostSettings: {
		// is_detect_port_enabled: true,
		is_tcp_enabled: true,
		is_udp_enabled: false,
		is_detect_os_enabled: true,
	},
	prelogin: {
		site_login: false,
		login_method: 'form',
		login_form_action_url: '',
		login_form_postdata: '',
		login_json_action_url: '',
		login_json_postdata: '',
		request_cookie: '',
		request_http_headers: '',
		is_http_auth_enabled: false,
		http_auth_username: '',
		http_auth_password: '',
		is_proxy_enabled: false,
		proxy_scheme: 'http',
		proxy_host: '',
		proxy_port: 80,
		proxy_username: '',
		proxy_password: '',
	},
	custom_monitor_page: {
		includeUrl: '',
		excludeUrl: '',
	},
	alert: {
		vulType: [],
	},
	task_type: 'http',
	aviliable_task_list: [],
	selected_aviliable_task_list: [],
	task_settings: {
		collect: {
			area: [],
			area_ipv6: [],
			method: 'get',
			header: '',
			redirect: ['3'],
		},
		alert: {
			respTime: 12000,
			enableSmartMode: true,
			innerType: 'statusCodeRange',
			statusCodeRange: '400~599',
			include: [],
			nodeCount: 5,
			alertCount: ['1'],
			enable: true,
			lossRate: 50,
		},
	},
	ws_task_time: {
		startType: 'now',
		startAt: '',
		periodEndTime: '',
		periodStartTime: '',
	},
};
const CONTENT_KEYWORD_TYPES_MAP = CONTENT_KEYWORD_TYPES.reduce((t, i) => {
	t[i.idx] = i.label;
	return t;
}, {});
const CONTENT_PRIVACY_DISCLOSURE_TYPES_MAP =
	CONTENT_PRIVACY_DISCLOSURE_TYPES.reduce((t, i) => {
		t[i.idx] = i.label;
		return t;
	}, {});
const intervalFormat = value => {
	let unit;
	let num;
	if (value) {
		const freq = ms(value);
		unit = value ? freq.replace(/\d*/, '') : 'd';
		num = parseInt(freq.replace(/[a-zA-Z]/, ''), 10);
		if (value % ms('30d') === 0) {
			unit = 'month';
			num = value / ms('30d');
		} else if (value % ms('1w') === 0) {
			unit = 'w';
			num = value / ms('1w');
		}
	}
	return `${num}${FREQUENCY_UNIT_MAP[unit]}`;
};

const contextToList = context => {
	if (!context || typeof context !== 'string') {
		return [];
	}
	return context.split('\n');
};

const changeTypeFormat = changeTypes => {
	if (!changeTypes) {
		return '- -';
	}
	return changeTypes
		.map(key => WARNING_CATEGORY_KEY_LABEL_MAP.changeCheck[key])
		.join('、');
};

const formatJobList = assetType => {
	const _formatJobList = item => {
		const noteWidth = assetType !== 'host' ? '25' : '35';
		const urlWidth = assetType !== 'host' ? '52' : '62';
		const webAssetSourceIp = `<span style="width: 18%;display: inline-block;margin-left: 10px;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;" title='${
			item.source_ip
		}'>${item.source_ip || ''}</span>`;
		const labelHtml = `
					<span style="width: ${noteWidth}%;display: inline-block;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;" title='${
			item.note
		}'>${item.note}</span>
					<span style="width: ${urlWidth}%;display: inline-block;margin-left: 10px;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;" title='${
			item.target_url
		}'>${item.target_url}</span>
					${assetType !== 'host' ? `${webAssetSourceIp}` : ''}`;
		const sourceIp =
			item.source_ip && assetType !== 'host'
				? '\t' + `(${item.source_ip})`
				: '';
		return {
			label: item.note + '\t' + item.target_url + sourceIp,
			labelHtml,
			cydEnabled: item.cydEnabled,
			value: item.job_id,
		};
	};
	return _formatJobList;
};

const formatJobMap = assetType => {
	const _formatJobMap = (total, item) => {
		total[item.job_id] =
			item.target_url +
			(item.source_ip && assetType !== 'host' ? `(${item.source_ip})` : '');
		return total;
	};
	return _formatJobMap;
};

function CreateJobAll({ history, location }) {
	const resD = JSON.parse(sessionStorage.resD || null) || {};
	const is_support =
		resD?.balance?.wsTaskTime?.total && resD?.feature?.wsTaskTime;
	const assetType = GetQueryString(location.search, 'assetType') || 'web';
	const atid = GetQueryString(location.search, 'atid');
	const jid = GetQueryString(location.search, 'jid');
	const isSchedule = JSON.parse(GetQueryString(location.search, 'isSchedule'));
	const [typeText, setTypeText] = useState([
		'新建监测任务',
		'创建任务',
		'下发任务',
	]);
	const [step, setStep] = useState(1);
	const [btnType, setBtnType] = useState('下一步');
	const [formData, setFormData] = useState(null);
	const [form] = Form.useForm();
	const [scheduleJobList, setScheduleJobList] = useState([]);
	const [manualJobList, setManualJobList] = useState([]);
	const [scheduleJobMap, setScheduleJobMap] = useState({});
	const [manualJobMap, setManualJobMap] = useState({});
	const [vulnsMap, setVulnsMap] = useState(null);
	const [vulnsList, setVulnsList] = useState([]);
	const [vulnsTemp, setVulnsTemp] = useState([]);
	const [deafultVulnTemp, setDeafultVulnTemp] = useState(['1']);
	const [taskInfoDialog, setTaskInfoDialog] = useState(false);
	const [isOnSubmit, setIsOnSubmit] = useState(false);
	const [hostSubmit, setHostSubmit] = useState(false);
	const [hostInfoDialog, setHostInfoDialog] = useState(false);

	defaultWebData.interval =
		resD?.balance?.hostVulMaxFreq?.total <= 604800000
			? 604800000
			: resD?.balance?.hostVulMaxFreq?.total;

	defaultWebData.vul_settings.interval =
		resD?.balance?.vulMaxFreq?.total <= 604800000
			? 604800000
			: resD?.balance?.vulMaxFreq?.total;
	defaultWebData.vul_settings.collect.depth = [
		resD?.balance?.vulMaxDepth?.total >= 3
			? 3
			: resD?.balance?.vulMaxDepth?.total,
	];
	defaultWebData.vul_settings.collect.maxPage = [
		resD?.balance?.vulMaxPage?.total >= 1000
			? 1000
			: resD?.balance?.vulMaxPage?.total,
	];

	defaultWebData.ssl_settings.interval =
		resD?.balance?.sslMaxFreq?.total <= 86400000
			? 86400000
			: resD?.balance?.sslMaxFreq?.total;

	defaultWebData.content_settings.interval =
		resD?.balance?.contentMaxFreq?.total <= 86400000
			? 86400000
			: resD?.balance?.contentMaxFreq?.total;
	defaultWebData.content_settings.collect.depth = [
		resD?.balance?.contentMaxDepth?.total >= 3
			? 3
			: resD?.balance?.contentMaxDepth?.total,
	];
	defaultWebData.content_settings.collect.maxPage = [
		resD?.balance?.contentMaxPage?.total >= 1000
			? 1000
			: resD?.balance?.contentMaxPage?.total,
	];

	defaultWebData.security_event_settings.interval =
		resD?.balance?.securityEventMaxFreq?.total <= 86400000
			? 86400000
			: resD?.balance?.securityEventMaxFreq?.total;
	defaultWebData.security_event_settings.collect.depth = [
		resD?.balance?.securityEventMaxDepth?.total >= 3
			? 3
			: resD?.balance?.securityEventMaxDepth?.total,
	];
	defaultWebData.security_event_settings.collect.maxPage = [
		resD?.balance?.securityEventMaxPage?.total >= 1000
			? 1000
			: resD?.balance?.securityEventMaxPage?.total,
	];

	defaultWebData.change_check_settings.interval =
		resD?.balance?.changeCheckMaxFreq?.total <= 86400000
			? 86400000
			: resD?.balance?.changeCheckMaxFreq?.total;
	defaultWebData.change_check_settings.collect.depth = [
		resD?.balance?.changeCheckMaxDepth?.total >= 3
			? 3
			: resD?.balance?.changeCheckMaxDepth?.total,
	];
	defaultWebData.change_check_settings.collect.maxPage = [
		resD?.balance?.changeCheckMaxPage?.total >= 1000
			? 1000
			: resD?.balance?.changeCheckMaxPage?.total,
	];
	defaultWebData.change_check_settings.collect.baseChangeCount = [
		resD?.balance?.changeCheckMaxBaseChange?.total <= 5
			? 5
			: resD?.balance?.changeCheckMaxBaseChange?.total,
	];

	// 漏洞插件
	const getVulnsList = async () => {
		const res = await fetchFer(`/api/v2/vulndb/kb_vulns`, {
			method: 'GET',
			checkStatus: 501,
		}).catch(err => {
			return err;
		});
		const mapData = {};
		const data = res.data.map(item => {
			mapData[item.source_id] = item.name.zh_cn;
			return { label: item.name.zh_cn, value: item.source_id };
		});
		setVulnsList(data);
		setVulnsMap(mapData);
	};

	// 漏洞模版
	const getVulnsTemp = async type => {
		const res = await fetchFer(`api/v2/kb/get_all_profile_names`, {
			method: 'GET',
			checkStatus: 501,
		}).catch(err => {
			return err;
		});
		const defaultVul = [];
		const data = res.data.map(item => {
			item.name === 'full' && defaultVul.push(item.value.toString());
			return {
				label: item.display_name.zh_cn,
				value: item.custom_profile_template_id || item.value.toString(),
			};
		});
		setVulnsTemp(data);
		setDeafultVulnTemp(defaultVul);
	};

	// 获取资产列表
	const getScheduleJobList = async () => {
		const task_group_type = assetType === 'host' ? 'host' : 'web_security';
		const url = `/api/v2/jobs/job_id_list?task_group_type=${task_group_type}&asset_type=${assetType}&trigger_type=schedule`;
		const res = await fetchFer(url, { method: 'GET' });
		if (res.code === 200) {
			setScheduleJobList(res.data.map(formatJobList(assetType)));
			setScheduleJobMap(res.data.reduce(formatJobMap(assetType), {}));
		}
	};
	const getManualJobList = async () => {
		const task_group_type = assetType === 'host' ? 'host' : 'web_security';
		const url = `/api/v2/jobs/job_id_list?task_group_type=${task_group_type}&asset_type=${assetType}&trigger_type=manual`;
		const res = await fetchFer(url, { method: 'GET' });
		if (res.code === 200) {
			setManualJobList(res.data.map(formatJobList(assetType)));
			setManualJobMap(res.data.reduce(formatJobMap(assetType), {}));
		}
	};

	const formDataChange = (name, info) => {
		if (
			info?.changedFields?.length > 0 &&
			!info.changedFields.filter(i => {
				return i.errors.length;
			}).length
		) {
			const finallyData = Object.assign(
				{},
				formData,
				info?.forms[name]?.getFieldValue()
			);
			if (
				assetType === 'web' &&
				info?.changedFields?.filter(i => {
					return i.name[0] === 'trigger_type';
				}).length > 0
			) {
				finallyData.vul_settings.enable = getTaskEnable(
					'vul',
					finallyData.trigger_type
				);
				finallyData.security_event_settings.enable = getTaskEnable(
					'securityEvent',
					finallyData.trigger_type
				);
				finallyData.content_settings.enable = getTaskEnable(
					'content',
					finallyData.trigger_type
				);
				finallyData.ssl_settings.enable = getTaskEnable(
					'ssl',
					finallyData.trigger_type
				);
				finallyData.change_check_settings.enable =
					finallyData.trigger_type !== 'manual' &&
					pathOr(0, ['feature', 'changeCheckTask'], resD);
				finallyData.vul_settings.vulType =
					finallyData?.trigger_type === 'manual' ? 'type' : 'all';
				finallyData.ws_task_time = {
					startType: 'now',
					startAt: '',
					periodEndTime: '',
					periodStartTime: '',
				};
				finallyData.job_ids = [];
				finallyData.ssl_settings.enable = isSslEnable(
					finallyData.trigger_type,
					finallyData.job_ids,
					manualJobMap
				);
			}

			if (
				assetType === 'web' &&
				info?.changedFields?.filter(i => {
					return i.name[0] === 'job_ids';
				}).length > 0
			) {
				finallyData.ssl_settings.enable = finallyData.ssl_settings.enable
					? isSslEnable(
							finallyData.trigger_type,
							finallyData.job_ids,
							manualJobMap
					  )
					: finallyData.ssl_settings.enable;
				if (finallyData.job_ids.length > 1) {
					// 多个监测目标时爬虫设置无效且清空
					finallyData.prelogin = {
						site_login: false,
						login_method: 'form',
						login_form_action_url: '',
						login_form_postdata: '',
						login_json_action_url: '',
						login_json_postdata: '',
						request_cookie: '',
						request_http_headers: '',
						is_http_auth_enabled: false,
						http_auth_username: '',
						http_auth_password: '',
						is_proxy_enabled: false,
						proxy_scheme: 'http',
						proxy_host: '',
						proxy_port: 80,
						proxy_username: '',
						proxy_password: '',
					};
					finallyData.custom_monitor_page = {
						excludeUrl: '',
						includeUrl: '',
					};
				}
			}
			if (
				assetType === 'web' &&
				info?.changedFields?.filter(i => {
					return i.name[1] === 'vulType';
				}).length > 0
			) {
				finallyData.vul_settings.collect.vul =
					finallyData?.collect?.vulType === 'all'
						? vulnsTemp.map(i => {
								return i.label;
						  })
						: finallyData.vul_settings.collect.vul;
			}
			if (
				assetType === 'web' &&
				info?.changedFields?.filter(i => {
					return (
						i.name[2] === 'systemKeywordStatus' ||
						i.name[2] === 'privacyDisclosureStatus'
					);
				}).length > 0
			) {
				finallyData.content_settings.collect.plugins = [];
				if (finallyData.content_settings.collect.systemKeywordStatus)
					finallyData.content_settings.collect.plugins.push('keyword');
				if (finallyData.content_settings.collect.privacyDisclosureStatus)
					finallyData.content_settings.collect.plugins.push(
						'privacy_disclosure'
					);
			}
			if (
				assetType === 'web' &&
				info?.changedFields?.filter(i => {
					return i.name[0] === 'content_settings' && i.name[1] === 'enable';
				}).length > 0
			) {
				if (finallyData.content_settings.enable) {
					finallyData.content_settings.collect.systemKeywordStatus = true;
					finallyData.content_settings.collect.privacyDisclosureStatus = true;
					finallyData.content_settings.collect.plugins = [
						'keyword',
						'privacy_disclosure',
					];
				} else {
					finallyData.content_settings.collect.systemKeywordStatus = false;
					finallyData.content_settings.collect.privacyDisclosureStatus = false;
					finallyData.content_settings.collect.plugins = [];
				}
			}
			if (
				assetType === 'web' &&
				info?.changedFields?.filter(i => {
					return (
						i.name[0] === 'vul_settings' &&
						i.name[1] === 'enableSitePortraitTriggerMonitor'
					);
				}).length > 0
			) {
				if (finallyData.vul_settings.enableSitePortraitTriggerMonitor) {
					Message.show({
						type: 'success',
						message: '网站画像监测引擎已启用',
					});
				}
			}
			setFormData(finallyData);
		}
	};

	// 更新任务
	const getUpdateData = async atid => {
		let url = `/api/v2/tasks/available/config/detail?asset_task_id=${atid}`;
		if (assetType === 'host') {
			url = `/api/v2/jobs/host_vul_task_settings?asset_task_id=${atid}`;
		} else if (assetType === 'web') {
			url = `/api/v2/tasks/web_security/config/detail?asset_task_id=${atid}`;
		}
		setTypeText(['编辑监测任务', '编辑任务', '保存']);
		const res = await fetchFer(url, { method: 'GET' });

		const params =
			assetType === 'host'
				? {
						name: res.data?.name,
						trigger_type: res.data?.trigger_type,
						jobId: res.data?.job_id,
						job_ids: [res.data?.job_id],
						job_name: res.data?.job_name,
						target_url: res.data?.target_url,
						source_ip: res.data?.source_ip,
						interval: res.data?.interval,
						hostSettings: {
							// is_detect_port_enabled: res.data?.is_detect_port_enabled,
							is_tcp_enabled: res.data?.is_tcp_enabled,
							is_udp_enabled: res.data?.is_udp_enabled,
							is_detect_os_enabled: res.data?.is_detect_os_enabled,
						},
				  }
				: Object.assign({}, defaultWebData, res.data);
		if (assetType === 'web') {
			params.trigger_type = params.triggerType;
			params.job_ids = params.jobId.split(',');
			params.vul_settings = cloneDeep(params.vulSettings);
			if (!getTaskEnable('vul', params.trigger_type)) {
				params.vul_settings.enable = false;
			}
			params.vul_settings.collect.depth = params.vul_settings.collect.depth
				? [params.vul_settings.collect.depth]
				: [];
			params.vul_settings.collect.maxPage = params.vul_settings.collect.maxPage
				? [params.vul_settings.collect.maxPage]
				: [];
			params.vul_settings.collect.speed = params.vul_settings.collect.speed
				? [params.vul_settings.collect.speed]
				: ['medium'];
			params.vul_settings.collect.includeUrl = params.vul_settings.collect
				.includeUrl
				? params.vul_settings.collect.includeUrl.join('\n')
				: '';
			if (params.vul_settings.collect.vul.length === vulnsTemp.length) {
				params.vul_settings.vulType = 'all';
			} else {
				params.vul_settings.vulType = 'notAll';
			}

			params.ssl_settings = cloneDeep(params.sslSettings);
			if (
				params.ssl_settings.collect.pluginCategories.length ===
				Object.keys(SSL_CATEGORY_KEY_LABEL_MAP).length
			) {
				params.ssl_settings.sslType = 'all';
			} else {
				params.ssl_settings.sslType = 'notAll';
			}
			// SSL是否可选
			const enableType = getTaskEnable('ssl', params.trigger_type);
			const hasHttps = params.targetUrl.startsWith('https');
			if (!enableType || !hasHttps) {
				params.ssl_settings.enable = false;
			}

			params.security_event_settings = cloneDeep(params.securityEventSettings);
			if (!getTaskEnable('securityEvent', params.trigger_type)) {
				params.security_event_settings.enable = false;
			}
			params.security_event_settings.collect.depth = params
				.security_event_settings.collect.depth
				? [params.security_event_settings.collect.depth]
				: [];
			params.security_event_settings.collect.maxPage = params
				.security_event_settings.collect.maxPage
				? [params.security_event_settings.collect.maxPage]
				: [];

			params.content_settings = cloneDeep(params.contentSettings);
			if (!getTaskEnable('content', params.trigger_type)) {
				params.content_settings.enable = false;
			}
			params.content_settings.collect.depth = params.content_settings.collect
				.depth
				? [params.content_settings.collect.depth]
				: [];
			params.content_settings.collect.maxPage = params.content_settings.collect
				.maxPage
				? [params.content_settings.collect.maxPage]
				: [];
			if (
				params.content_settings.collect.plugins.indexOf('privacy_disclosure') >
				-1
			)
				params.content_settings.collect.privacyDisclosureStatus = true;
			if (params.content_settings.collect.plugins.indexOf('keyword') > -1)
				params.content_settings.collect.systemKeywordStatus = true;
			if (params.content_settings.collect.includeUrl.length > 0) {
				params.content_settings.collect.includeUrl =
					params.content_settings.collect.includeUrl.join('\n');
				params.content_settings.type = 'assign';
			} else {
				params.content_settings.type = 'full';
				params.content_settings.collect.includeUrl = '/';
			}

			params.change_check_settings = cloneDeep(params.changeCheckSettings);
			if (!pathOr(0, ['feature', 'changeCheckTask'], resD)) {
				params.change_check_settings.enable = false;
			}
			params.change_check_settings.collect.depth = params.change_check_settings
				.collect.depth
				? [params.change_check_settings.collect.depth]
				: [];
			params.change_check_settings.collect.maxPage = params
				.change_check_settings.collect.maxPage
				? [params.change_check_settings.collect.maxPage]
				: [];
			params.change_check_settings.collect.baseChangeCount = params
				.change_check_settings.collect.baseChangeCount
				? [params.change_check_settings.collect.baseChangeCount]
				: [];
			params.change_check_settings.collect.excludeUrl = params
				.change_check_settings.collect.excludeUrl
				? params.change_check_settings.collect.excludeUrl.join('\n')
				: '';
			params.change_check_settings.collect.includeUrl = params
				.change_check_settings.collect.includeUrl
				? params.change_check_settings.collect.includeUrl.join('\n')
				: '';
			params.change_check_settings.collect.keywords = params
				.change_check_settings.collect.keywords
				? params.change_check_settings.collect.keywords.join('\n')
				: '';
			params.change_check_settings.collect.resources = params
				.change_check_settings.collect.resources
				? params.change_check_settings.collect.resources.join('\n')
				: '';

			params.custom_monitor_page = cloneDeep(params.customMonitorPage);
			params.custom_monitor_page.includeUrl = params.custom_monitor_page
				.includeUrl
				? params.custom_monitor_page.includeUrl.join('\n')
				: '';
			params.custom_monitor_page.excludeUrl = params.custom_monitor_page
				.excludeUrl
				? params.custom_monitor_page.excludeUrl.join('\n')
				: '';
			if (params.ws_task_time.periodStartTime) {
				const [h, m] = moment(
					new Date(
						moment().format('YYYY-MM-DD ') + params.ws_task_time.periodStartTime
					)
				)
					.format('HH:mm')
					.split(':');
				params.ws_task_time.periodStartTime = moment().set({ h, m });
			}
			if (params.ws_task_time.periodEndTime) {
				const [h, m] = moment(
					new Date(
						moment().format('YYYY-MM-DD ') + params.ws_task_time.periodEndTime
					)
				)
					.format('HH:mm')
					.split(':');
				params.ws_task_time.periodEndTime = moment().set({ h, m });
			}
			if (params.ws_task_time.startAt) {
				params.ws_task_time.startType = 'time';
				params.ws_task_time.startAt = moment(data.ws_task_time.startAt);
			}
		}
		setFormData(params);
	};

	// 根据某一个资产创建任务
	const getJobData = jid => {
		const data = JSON.parse(JSON.stringify(defaultWebData));
		data.job_ids = [jid];
		if (!isSchedule) {
			data.trigger_type = 'manual';
			data.vul_settings.vulType = 'type';
		} else {
			data.trigger_type = 'schedule';
			data.vul_settings.vulType = 'all';
		}
		setFormData(data);
	};
	// 创建任务
	const createNewTask = () => {
		const formData = JSON.parse(JSON.stringify(defaultWebData));
		formData.vul_settings.collect.vul = deafultVulnTemp;
		if (formData.ws_task_time.periodStartTime) {
			const [h, m] = moment(
				new Date(
					moment().format('YYYY-MM-DD ') + formData.ws_task_time.periodStartTime
				)
			)
				.format('HH:mm')
				.split(':');
			formData.ws_task_time.periodStartTime = moment().set({ h, m });
		}
		if (formData.ws_task_time.periodEndTime) {
			const [h, m] = moment(
				new Date(
					moment().format('YYYY-MM-DD ') + formData.ws_task_time.periodEndTime
				)
			)
				.format('HH:mm')
				.split(':');
			formData.ws_task_time.periodEndTime = moment().set({ h, m });
		}
		if (formData.ws_task_time.startAt) {
			formData.ws_task_time.startType = 'time';
			formData.ws_task_time.startAt = moment(formData.ws_task_time.startAt);
		}
		setFormData(formData);
	};
	const showRes = type => {
		form.validateFields().then(async res => {
			if (!res) return false;
			const sendData = Object.assign({}, formData);
			if (atid) {
				const vulList = vulnsTemp.map(i => {
					return i.value;
				});
				const vul = sendData.vul_settings.collect.vul.filter(i => {
					return vulList.includes(i);
				});
				if (step !== 2 && vul.length === 0) {
					return Message.show({
						type: 'error',
						message: '漏洞策略模板已被删除，请重新选择',
					});
				}
			}
			let text = '若不进行任务配置将采用默认配置，您确定要现在下发任务吗？';
			if (step === 2) {
				text = '您确定要下发任务吗？';
			}
			if (atid) {
				text = '您确定保存当前任务配置？';
			}
			if (!type) {
				Confirm({
					title: '提示',
					className: s.w472,
					message: <div className={s.p20_40}>{text}</div>,
					onconfirm: async () => {
						setIsOnSubmit(false);
						setTaskInfoDialog(true);
					},
					oncancel: () => {},
				});
			} else {
				setIsOnSubmit(false);
				setTaskInfoDialog(true);
			}
			Object.keys(sendData).map(key => {
				if (
					typeof sendData[key] === 'object' &&
					!(sendData[key] instanceof Array)
				) {
					sendData[key] = cloneDeep(sendData[key], defaultWebData[key]);
				}
			});
			if (type) {
				if (isOnSubmit) return false;
				setIsOnSubmit(true);
				const data = cloneDeep(sendData);
				let url = '';
				if (!atid) {
					if (data.trigger_type === 'schedule') {
						url = '/api/v2/jobs/web_security/task/add';
					} else {
						url = '/api/v2/jobs/web_security/task/manual/add';
					}
				} else {
					url = '/api/v2/jobs/web_security/task/update';
					data.asset_task_id = atid;
				}
				// 监测方式
				data.vul_settings.collect.speed = data.vul_settings.collect.speed[0];
				data.vul_settings.collect.depth = data.vul_settings.collect.depth[0];
				data.vul_settings.collect.maxPage =
					data.vul_settings.collect.maxPage[0];
				if (data.vul_settings.vulType === 'plugIn') {
					data.vul_settings.collect.vul = data.vul_settings.collect.vulns;
				}
				data.vul_settings.collect.includeUrl = data.vul_settings.collect
					.includeUrl
					? data.vul_settings.collect.includeUrl.split('\n')
					: [];

				// ssl
				if (data.ssl_settings.sslType === 'all')
					data.ssl_settings.collect = {
						pluginCategories: Object.keys(SSL_CATEGORY_KEY_LABEL_MAP),
					};

				// security
				data.security_event_settings.collect.depth =
					data.security_event_settings.collect.depth[0];
				data.security_event_settings.collect.maxPage =
					data.security_event_settings.collect.maxPage[0];
				// content
				data.content_settings.collect.depth =
					data.content_settings.collect.depth[0];
				data.content_settings.collect.maxPage =
					data.content_settings.collect.maxPage[0];
				if (data.content_settings.type === 'assign') {
					data.content_settings.collect.includeUrl = data.content_settings
						.collect.includeUrl
						? data.content_settings.collect.includeUrl.split('\n')
						: [];
				} else {
					data.content_settings.collect.includeUrl = [];
				}
				data.content_settings.collect.plugins = [];
				if (data.content_settings.collect.privacyDisclosureStatus)
					data.content_settings.collect.plugins.push('privacy_disclosure');
				if (data.content_settings.collect.systemKeywordStatus)
					data.content_settings.collect.plugins.push('keyword');

				// 篡改 change_check
				data.change_check_settings.collect.depth =
					data.change_check_settings.collect.depth[0];
				data.change_check_settings.collect.maxPage =
					data.change_check_settings.collect.maxPage[0];
				data.change_check_settings.collect.baseChangeCount =
					data.change_check_settings.collect.baseChangeCount[0];
				data.change_check_settings.collect.keywords = data.change_check_settings
					.collect.keywords
					? data.change_check_settings.collect.keywords.split('\n')
					: [];
				data.change_check_settings.collect.resources = data
					.change_check_settings.collect.resources
					? data.change_check_settings.collect.resources.split('\n')
					: [];
				if (data.change_check_settings.collect.type === 'part') {
					data.change_check_settings.collect.includeUrl = data
						.change_check_settings.collect.includeUrl
						? data.change_check_settings.collect.includeUrl.split('\n')
						: [];
					data.change_check_settings.collect.excludeUrl = data
						.change_check_settings.collect.excludeUrl
						? data.change_check_settings.collect.excludeUrl.split('\n')
						: [];
				} else {
					data.change_check_settings.collect.includeUrl = [];
					data.change_check_settings.collect.excludeUrl = [];
				}
				// 指定页面
				data.custom_monitor_page.includeUrl = data.custom_monitor_page
					.includeUrl
					? data.custom_monitor_page.includeUrl.split('\n')
					: [];
				data.custom_monitor_page.excludeUrl = data.custom_monitor_page
					.excludeUrl
					? data.custom_monitor_page.excludeUrl.split('\n')
					: [];

				if (data.ws_task_time.startType === 'now') {
					data.ws_task_time.startAt = '';
				}
				if (data.ws_task_time.periodStartTime)
					data.ws_task_time.periodStartTime = moment(
						data.ws_task_time.periodStartTime
					)
						.seconds(0)
						.format('HH:mm:ss');
				if (data.ws_task_time.periodEndTime)
					data.ws_task_time.periodEndTime = moment(
						data.ws_task_time.periodEndTime
					)
						.seconds(0)
						.format('HH:mm:ss');
				const {
					asset_task_id,
					content_settings,
					custom_monitor_page,
					hostSettings,
					job_ids,
					name,
					prelogin,
					security_event_settings,
					ssl_settings,
					task_settings,
					trigger_type,
					vul_settings,
					ws_task_time,
					change_check_settings,
				} = data;
				const res = await fetchFer(url, {
					method: 'POST',
					body: JSON.stringify(
						formatSubmitData(
							{
								asset_task_id,
								content_settings,
								custom_monitor_page,
								hostSettings,
								job_ids,
								name,
								prelogin,
								security_event_settings,
								ssl_settings,
								task_settings,
								trigger_type,
								vul_settings,
								ws_task_time,
								change_check_settings,
							},
							'web'
						)
					),
					checkStatus: 501,
				}).catch(err => {
					return err;
				});
				setTaskInfoDialog(false);
				getResD();
				setIsOnSubmit(false);
				Message.show({
					type: res.status || (res.code === 200 ? 'success' : 'error'),
					message: res.message || res.msg,
					onclose() {
						if (res.code === 200) {
							if (atid) {
								window.history.back();
							} else {
								window.location.href = '/#/job-manage/web-task';
							}
						}
					},
				});
			}
		});
	};

	const sendFun = async type => {
		const sendData = Object.assign({}, formData);
		let text = '若不进行任务配置将采用默认配置，您确定要现在下发任务吗？';
		if (step === 2) {
			text = '您确定要下发任务吗？';
		}
		if (atid) {
			text = '您确定保存当前任务配置？';
		}
		if (!type) {
			Confirm({
				title: '提示',
				className: s.w472,
				message: <div className={s.p20_40}>{text}</div>,
				onconfirm: async () => {
					setHostSubmit(false);
					setHostInfoDialog(true);
				},
				oncancel: () => {},
			});
		} else {
			setHostSubmit(false);
			setHostInfoDialog(true);
		}
		if (type) {
			if (hostSubmit) return false;
			setHostSubmit(true);
			const params = {
				name: sendData.name,
				trigger_type: sendData.trigger_type,
				job_ids: sendData.job_ids,
				interval: sendData.interval,
				// is_detect_port_enabled: sendData.hostSettings.is_detect_port_enabled,
				is_tcp_enabled: sendData.hostSettings.is_tcp_enabled,
				is_udp_enabled: sendData.hostSettings.is_udp_enabled,
				is_detect_os_enabled: sendData.hostSettings.is_detect_os_enabled,
			};
			if (atid) {
				params.asset_task_id = atid;
			}
			const res = await fetchFer(`/api/v2/jobs/host_vul_task`, {
				method: 'POST',
				body: JSON.stringify(formatSubmitData(params, 'host')),
				checkStatus: 501,
			}).catch(err => {
				return err;
			});
			if (res.code === 200 || res.code === 0) {
				Message.show({
					type: 'success',
					message: res.message || res.msg,
					placement: 'top',
				});
				setHostSubmit(false);
				if (atid) {
					window.history.back();
				} else {
					history.push(`/job-manage/host-task`);
				}
			} else {
				setHostSubmit(false);
				Message.show({
					type: 'error',
					message: res.msg,
					placement: 'top',
				});
			}
		}
	};

	const taskContent = (data, map) => {
		const foreignLinksMap = {
			foreign_links_2: '违规内容',
			foreign_links_3: '风险域名',
			foreign_links_1: '未备案',
		};
		const foreignText = [];
		const mapKeyList = Object.entries(map)?.map(i => {
			return i[0];
		});
		const allData = mapKeyList
			?.reduce((t, i) => {
				data.indexOf(i) > -1 && t.push(i);
				return t;
			}, [])
			?.reduce((t, item) => {
				if (foreignLinksMap[item]) {
					foreignText.push(foreignLinksMap[item]);
					foreignText.length === 1 && t.push('风险外链');
				} else {
					t.push(map[item]);
				}
				return t;
			}, []);
		return allData
			?.filter(i => i !== '风险外链')
			?.concat(
				foreignText.length > 0 ? `风险外链(${foreignText.join('、')})` : ''
			)
			?.filter(i => i)
			?.join('、');
	};

	const mockItems = [
		{ key: '1', label: 'x.x.x.x' },
		{ key: '2', label: 'x.x.x.x' },
		{ key: '3', label: 'x.x.x.x' },
	];
	useEffect(() => {
		getScheduleJobList();
		getManualJobList();
		getVulnsList();
		getVulnsTemp();
	}, []);
	useEffect(() => {
		setFormData(null);
		if (jid) {
			getJobData(jid);
		} else if (atid) {
			getUpdateData(atid);
		} else {
			createNewTask();
		}
	}, [jid, atid]);
	// 眼状数据展示图标
	const EyesTip = ({ data, line }) => (
		<Tooltip
			overlay={
				<div
					style={{
						maxWidth: '500px',
						// maxHeight: '300px',
						overflow: 'auto',
					}}
				>
					{line ? data.map(item => <p>{item}、</p>) : data}
				</div>
			}
			placement={'top'}
		>
			<Icon type={'detail'} className={cn(s.mainColor, s.cp, s.ml5, s.vam)} />
		</Tooltip>
	);

	const formatChangeCheckConfig = stringData => {
		const listData = contextToList(stringData);
		const count = listData.length;
		if (!count > 0) {
			return '- -';
		}
		if (count === 1) {
			return listData[0];
		}
		return (
			<span>
				{listData[0]}等{count}个<EyesTip data={listData} line={true} />
			</span>
		);
	};

	return (
		<div className={s.body}>
			<Breadcrumb className={s.bread}>
				<Item key={`job-manage`} disabled>
					任务管理
				</Item>
				<Item key={`${assetType}-task`}>
					{_.get(ASSET_TASK_TYPE_MAP, assetType, '')}
				</Item>
				<Item key={`action-task`}>{typeText[0]}</Item>
			</Breadcrumb>
			<div className={cn(s.content, s.con)}>
				<div className={s.allstep}>
					<div className={cn(s.step, step !== 1 ? s.grey : false)}>
						{step !== 1 && <Success9 className={cn(s.iconsize, s.vam)} />}
						<span className={cn(s.dib, s.vam)}>{typeText[1]}</span>
						<span className={s.single}></span>
					</div>
					<div className={cn(s.step, s.ml10, step !== 2 ? s.grey : false)}>
						<span className={cn(s.dib, s.vam)}>配置参数</span>
						<span className={s.front}></span>
					</div>
				</div>
				<Form.Provider
					onFormChange={formDataChange}
					onFormFinish={(name, { forms, values }) => {
						if (btnType === '下一步') {
							setStep(2);
						} else if (btnType === '上一步') {
							setStep(1);
						} else if (btnType === '下发任务' || btnType === '保存配置') {
							if (assetType === 'web') showRes();
							if (assetType === 'host') sendFun();
						}
					}}
				>
					<Form form={form}>
						{step === 1 && (
							<WebStep1
								scheduleJobList={scheduleJobList}
								scheduleJobMap={scheduleJobMap}
								manualJobList={manualJobList}
								manualJobMap={manualJobMap}
								setBtnType={setBtnType}
								data={{ ...formData }}
								jid={jid}
								atid={atid}
								assetType={assetType}
							/>
						)}
						{step === 2 && (
							<WebStep2
								scheduleJobList={scheduleJobList}
								scheduleJobMap={scheduleJobMap}
								manualJobList={manualJobList}
								manualJobMap={manualJobMap}
								setBtnType={setBtnType}
								vulnsTemp={vulnsTemp}
								data={formData}
								atid={atid}
								assetType={assetType}
							/>
						)}
					</Form>
				</Form.Provider>
			</div>
			<Dialog
				visible={taskInfoDialog}
				onhide={() => {
					setIsOnSubmit(false);
					setTaskInfoDialog(false);
				}}
				onsubmit={() => showRes(true)}
				title="监测配置"
				confirmText={
					<Button type="primary" disabled={isOnSubmit}>
						{atid ? '保存' : '下发任务'}
					</Button>
				}
				className={cn(s.w720, s.t5vh, s.submitDialog)}
			>
				<div className={cn('pb10 pl20 pr20 pt20', s.mh65p, s.ofa)}>
					<div className={cn(s.df, s.aic, s.bd)}>
						<div className={cn(s.p10_20)}>任务名称</div>
						<div className={cn(s.p10_20, s.bdl, s.flex1)}>{formData?.name}</div>
					</div>
					<div className={cn(s.df, s.aic, s.bd)}>
						<div className={cn(s.p10_20)}>资产地址</div>
						<div className={cn(s.p10_20, s.bdl, s.flex1)}>
							{(function () {
								let jls = manualJobList;
								let ids = formData?.job_ids || [];
								if (formData?.trigger_type === 'schedule' && !atid && !jid) {
									jls = scheduleJobList;
								} else {
									jls = manualJobList;
								}
								function res(idList) {
									return jls.reduce((total, item) => {
										if (idList.indexOf(item.value) > -1) {
											total.push(item.label);
										}
										return total;
									}, []);
								}
								return ids.length > 5 ? (
									<div>
										{res(ids.slice(0, 5)).map((i, k) => {
											return (
												<div className="df aic">
													{i}
													{k === 4 && (
														<>
															<div>等{ids.length}个资产地址</div>
															<EyesTip
																data={res(ids).map(i => {
																	return <div>{i}</div>;
																})}
															/>
														</>
													)}
												</div>
											);
										})}
									</div>
								) : (
									res(ids).map(i => {
										return <div>{i}</div>;
									})
								);
							})()}
						</div>
					</div>
					<div className={cn(s.df, s.aic, s.bd)}>
						<div className={cn(s.p10_20)}>任务类型</div>
						<div className={cn(s.p10_20, s.bdl, s.flex1)}>
							{formData?.trigger_type === 'schedule' ? '周期性' : '单次'}任务
						</div>
					</div>
					{is_support ? (
						<div className={cn(s.df, s.aic, s.bd)}>
							<div className={cn(s.p10_20)}>
								{formData?.trigger_type === 'schedule'
									? '监测时间段'
									: '执行方式'}
							</div>
							<div className={cn(s.p10_20, s.bdl, s.flex1)}>
								{formData?.trigger_type === 'schedule'
									? formData?.ws_task_time?.periodStartTime &&
									  formData?.ws_task_time?.periodEndTime
										? `${moment(formData?.ws_task_time?.periodStartTime).format(
												'HH:mm'
										  )} - ${moment(
												formData?.ws_task_time?.periodEndTime
										  ).format('HH:mm')}`
										: '- -'
									: formData?.ws_task_time?.startType === 'now'
									? '立即执行'
									: `定时执行：${moment(formData?.ws_task_time?.startAt).format(
											'YYYY-MM-DD HH:mm:ss'
									  )}`}
							</div>
						</div>
					) : (
						''
					)}
					{formData?.vul_settings?.enable && (
						<div className={cn(s.df, s.aic, s.bd)}>
							<div className={cn(s.p10_20)}>Web漏洞</div>
							<div className={cn(s.p10_20, s.bdl, s.flex1)}>
								<div className={cn(s.subItem, s.df, s.aic)}>
									{formData?.trigger_type === 'schedule' &&
										!formData?.vul_settings
											?.enableSitePortraitTriggerMonitor && (
											<span>
												监测频率：
												{intervalFormat(formData?.vul_settings?.interval)}1次
											</span>
										)}
									{formData?.trigger_type === 'schedule' && (
										<span>
											监测方式：
											{formData?.vul_settings?.collect?.type === 'increment'
												? '增量监测'
												: '全量监测'}
										</span>
									)}
									<span className="w100p">
										监测内容：
										<span>
											{formData?.vul_settings?.vulType === 'plugIn' ? (
												formData?.vul_settings?.collect?.vulns.length > 0 ? (
													<>
														{formData?.vul_settings?.collect?.vulns
															?.slice(0, 2)
															.map(item => {
																return vulnsMap[item];
															})
															.join('、')}
														{formData?.vul_settings?.collect?.vulns.length >
															2 && (
															<>
																等
																{formData?.vul_settings?.collect?.vulns?.length}
																类
																<EyesTip
																	data={formData?.vul_settings?.collect?.vulns
																		?.map(item => vulnsMap[item])
																		.join('、')}
																/>
															</>
														)}
													</>
												) : (
													'- -'
												)
											) : formData?.vul_settings?.collect?.vul?.length > 0 ? (
												<>
													{formData?.vul_settings?.collect?.vul
														?.slice(0, 2)
														.map(item => {
															return vulnsTemp?.filter(i => {
																return i.value.toString() === item;
															})[0]?.label;
														})
														.join('、')}
													{formData?.vul_settings?.collect?.vul?.length > 2 && (
														<>
															等{formData?.vul_settings?.collect?.vul?.length}项
															<EyesTip
																data={formData?.vul_settings?.collect?.vul
																	?.map(
																		item =>
																			vulnsTemp?.filter(i => {
																				return i.value.toString() === item;
																			})[0]?.label
																	)
																	.join('、')}
															/>
														</>
													)}
												</>
											) : (
												'- -'
											)}
										</span>
									</span>
								</div>
								<div className={cn(s.subItem, s.df, s.aic)}>
									{formData?.trigger_type === 'schedule' &&
									formData?.vul_settings?.collect?.type === 'increment' ? (
										formData?.vul_settings?.enableSitePortraitTriggerMonitor ? (
											<span>网站画像监测引擎: 已启用</span>
										) : (
											''
										)
									) : (
										<span>
											监测深度：{formData?.vul_settings?.collect?.depth[0]}层
										</span>
									)}
									{formData?.trigger_type === 'schedule' &&
										formData?.vul_settings?.collect?.type !== 'increment' && (
											<span>
												监测模式：
												{formData?.vul_settings?.collect?.speed
													? formData?.vul_settings?.collect?.speed[0] === 'high'
														? '仅高危'
														: '高、中、低危'
													: ''}
											</span>
										)}
									{(formData?.vul_settings?.collect?.type !== 'increment' ||
										formData?.trigger_type !== 'schedule') && (
										<span>
											监测最大URL数：
											{formData?.vul_settings?.collect?.maxPage[0]}
										</span>
									)}
								</div>
							</div>
						</div>
					)}
					{formData?.ssl_settings?.enable && (
						<div className={cn(s.df, s.aic, s.bd)}>
							<div className={cn(s.p10_20)}>SSL安全</div>
							<div className={cn(s.p10_20, s.bdl, s.flex1)}>
								<div className={cn(s.subItem, s.df, s.aic)}>
									{formData?.trigger_type === 'schedule' && (
										<span>
											监测频率：
											{intervalFormat(formData?.ssl_settings?.interval)}1次
										</span>
									)}
									<span>
										监测内容：
										<span>
											{formData?.ssl_settings?.collect?.pluginCategories
												?.map(item => {
													return SSL_CATEGORY_KEY_LABEL_MAP[item];
												})
												.join('、')}
										</span>
									</span>
								</div>
							</div>
						</div>
					)}
					{formData?.security_event_settings?.enable && (
						<div className={cn(s.df, s.aic, s.bd)}>
							<div className={cn(s.p10_20)}>安全事件</div>
							<div className={cn(s.p10_20, s.bdl, s.flex1)}>
								<div className={cn(s.subItem, s.df, s.aic)}>
									{formData?.trigger_type === 'schedule' && (
										<span>
											监测频率：
											{intervalFormat(
												formData?.security_event_settings?.interval
											)}
											1次
										</span>
									)}
									<span>
										监测内容：
										{formData?.security_event_settings?.collect?.plugins
											?.length > 0 ? (
											<span>
												{taskContent(
													formData?.security_event_settings?.collect?.plugins,
													SECURITY_EVENT_TYPE_MAP
												)}
											</span>
										) : (
											'- -'
										)}
									</span>
								</div>
								<div className={cn(s.subItem, s.df, s.aic)}>
									<span>
										监测深度：
										{formData?.security_event_settings?.collect?.depth[0]}层
									</span>
									<span>
										监测最大URL数：
										{formData?.security_event_settings?.collect?.maxPage[0]}
									</span>
								</div>
							</div>
						</div>
					)}
					{formData?.content_settings?.enable && (
						<div className={cn(s.df, s.aic, s.bd)}>
							<div className={cn(s.p10_20)}>内容违规</div>
							<div className={cn(s.p10_20, s.bdl, s.flex1)}>
								<div className={cn(s.subItem, s.df, s.aifs)}>
									{formData?.trigger_type === 'schedule' && (
										<span>
											监测频率：
											{intervalFormat(formData?.content_settings?.interval)}1次
										</span>
									)}
									<span>
										监测方式：
										{formData?.content_settings?.type === 'assign'
											? '指定页面监测'
											: '全量监测'}
									</span>
									<span>
										监测内容：
										<span className={cn(s.dib, s.vat)}>
											{formData?.content_settings?.collect
												?.systemKeywordStatus ? (
												<>
													<span>
														敏感词(
														{formData?.content_settings?.collect
															?.systemKeywordTypes?.length > 0 ? (
															<>
																{formData?.content_settings?.collect?.systemKeywordTypes
																	?.slice(0, 2)
																	.map(item => {
																		return CONTENT_KEYWORD_TYPES_MAP[item];
																	})
																	.join('、')}
																{formData?.content_settings?.collect
																	?.systemKeywordTypes?.length > 2 &&
																	`等${formData?.content_settings?.collect?.systemKeywordTypes?.length}类`}
																{formData?.content_settings?.collect
																	?.systemKeywordTypes?.length > 2 && (
																	<EyesTip
																		data={formData?.content_settings?.collect?.systemKeywordTypes
																			?.map(
																				item => CONTENT_KEYWORD_TYPES_MAP[item]
																			)
																			.join('、')}
																	/>
																)}
															</>
														) : (
															'- -'
														)}
														)、
													</span>
													<br />
												</>
											) : (
												''
											)}
											{formData?.content_settings?.collect
												?.privacyDisclosureStatus ? (
												<span>
													隐私信息(
													{formData?.content_settings?.collect
														?.privacyDisclosureTypes?.length > 0 ? (
														<>
															{formData?.content_settings?.collect?.privacyDisclosureTypes
																?.slice(0, 2)
																.map(item => {
																	return CONTENT_PRIVACY_DISCLOSURE_TYPES_MAP[
																		item
																	];
																})
																.join('、')}
															{formData?.content_settings?.collect
																?.privacyDisclosureTypes?.length > 2 &&
																`等${formData?.content_settings?.collect?.privacyDisclosureTypes?.length}类`}
															{formData?.content_settings?.collect
																?.privacyDisclosureTypes?.length > 2 && (
																<EyesTip
																	data={formData?.content_settings?.collect?.privacyDisclosureTypes
																		?.map(
																			item =>
																				CONTENT_PRIVACY_DISCLOSURE_TYPES_MAP[
																					item
																				]
																		)
																		.join('、')}
																/>
															)}
														</>
													) : (
														'- -'
													)}
													)
												</span>
											) : (
												''
											)}
										</span>
									</span>
								</div>
								{formData?.content_settings.type === 'assign' &&
									(formData?.content_settings.collect.includeUrl ? (
										<span>
											指定页面:{' '}
											{formData?.content_settings.collect?.includeUrl?.split(
												'\n'
											)}
										</span>
									) : (
										''
									))}
								{formData?.content_settings.type !== 'assign' && (
									<div className={cn(s.subItem, s.df, s.aic)}>
										<span>
											监测深度：{formData?.content_settings?.collect?.depth[0]}
											层
										</span>
										<span>
											监测最大URL数：
											{formData?.content_settings?.collect?.maxPage[0]}
										</span>
									</div>
								)}
							</div>
						</div>
					)}
					{formData?.change_check_settings?.enable &&
						formData?.trigger_type === 'schedule' && (
							<div className={cn(s.df, s.aic, s.bd)}>
								<div className={cn(s.p10_20)}>篡改监测</div>
								<div className={cn(s.p10_20, s.bdl, s.flex1)}>
									<div className={cn(s.subItem, s.df, s.aifs)}>
										<span>
											监测频率：
											{intervalFormat(
												formData?.change_check_settings?.interval
											)}
											1次
										</span>
										<span>
											监测方式：
											{formData?.change_check_settings?.collect?.type === 'part'
												? '指定页面监测'
												: '全量监测'}
										</span>
									</div>

									<div className={cn(s.subItem, s.df, s.aifs)}>
										<span className={cn(s.dib, s.vat)}>
											<span>
												变更类型：
												{changeTypeFormat(
													formData?.change_check_settings?.collect?.changeType
												)}
											</span>
											<br />
											<span>
												重点关注资源：
												{formatChangeCheckConfig(
													formData?.change_check_settings?.collect?.resources
												)}
											</span>
											<br />
											<span>
												自定义敏感词：
												{formatChangeCheckConfig(
													formData?.change_check_settings?.collect?.keywords
												)}
											</span>
										</span>
									</div>
									{formData?.change_check_settings?.collect?.type ===
										'part' && (
										<div className={cn(s.subItem, s.df, s.aifs)}>
											<span>
												指定页面:{' '}
												{formatChangeCheckConfig(
													formData?.change_check_settings.collect?.includeUrl
												)}
											</span>
										</div>
									)}

									{formData?.change_check_settings?.collect?.type !==
										'part' && (
										<div className={cn(s.subItem, s.df, s.aic)}>
											<span>
												监测深度：
												{formData?.change_check_settings?.collect?.depth[0]}层
											</span>
											<span>
												监测最大URL数：
												{formData?.change_check_settings?.collect?.maxPage[0]}
											</span>
										</div>
									)}
									<div className={cn(s.subItem, s.df, s.aifs)}>
										{formData?.change_check_settings?.collect
											?.enableBaseChange ? (
											<span>
												自动更新样本频率: 每监测
												{formData?.change_check_settings?.collect
													?.baseChangeCount[0] || 5}
												次,系统将覆盖更新一次样本信息
											</span>
										) : (
											<span>自动更新样本频率: 未开启</span>
										)}
									</div>
								</div>
							</div>
						)}
					{formData?.job_ids?.length === 1 &&
						(formData?.prelogin?.site_login ||
							formData?.prelogin?.is_http_auth_enabled ||
							formData?.prelogin?.is_proxy_enabled) && (
							<div className={cn(s.df, s.aic, s.bd)}>
								<div className={cn(s.p10_20)}>预登录</div>
								<div className={cn(s.p10_20, s.bdl, s.flex1)}>
									<div className={s.mb10}>
										网站登录：{formData?.prelogin?.site_login ? '已' : '未'}
										设置
									</div>
									<div className={s.mb10}>
										HTTP认证：
										{formData?.prelogin?.is_http_auth_enabled ? '已' : '未'}
										设置
									</div>
									<div>
										代理服务器：
										{formData?.prelogin?.is_proxy_enabled ? '已' : '未'}设置
									</div>
								</div>
							</div>
						)}
					{formData?.job_ids?.length === 1 &&
						(formData?.custom_monitor_page?.includeUrl ||
							formData?.custom_monitor_page?.excludeUrl) && (
							<div className={cn(s.df, s.aic, s.bd)}>
								<div className={cn(s.p10_20)}>自定义监测页面</div>
								<div className={cn(s.p10_20, s.bdl, s.flex1)}>
									<div className={s.mb10}>
										需要额外监测页面入口：
										{formData?.custom_monitor_page?.includeUrl
											? formData?.custom_monitor_page?.includeUrl?.split('\n')
													.length > 0
												? '已设置'
												: '未设置'
											: '未设置'}
									</div>
									<div>
										不需要监测页面：
										{formData?.custom_monitor_page?.excludeUrl
											? formData?.custom_monitor_page?.excludeUrl?.split('\n')
													.length > 0
												? '已设置'
												: '未设置'
											: '未设置'}
									</div>
								</div>
							</div>
						)}
				</div>
				{atid && (
					<div className="warning-color pl20">
						您修改的配置将在下一周期生效。
					</div>
				)}
			</Dialog>
			<Dialog
				title="监测配置"
				className={cn(s.w720, s.submitDialog)}
				visible={hostInfoDialog}
				onhide={() => {
					setHostSubmit(false);
					setHostInfoDialog(false);
				}}
				onsubmit={() => sendFun(formData)}
				confirmText={
					<Button type="primary" disabled={hostSubmit}>
						{atid ? '保存' : '下发任务'}
					</Button>
				}
			>
				<div className={cn('pl20 pr20 pt20 pb10', s.mh65p, s.ofa)}>
					<div className={cn(s.df, s.aic, s.bd)}>
						<div className={cn(s.p10_20)}>任务名称</div>
						<div className={cn(s.p10_20, s.bdl, s.flex1)}>{formData?.name}</div>
					</div>
					<div className={cn(s.df, s.aic, s.bd)}>
						<div className={cn(s.p10_20)}>资产地址</div>
						<div className={cn(s.p10_20, s.bdl, s.flex1)}>
							{(function () {
								let jls = manualJobList;
								let ids = formData?.job_ids || [];
								if (formData?.trigger_type === 'schedule' && !atid && !jid) {
									jls = scheduleJobList;
								} else {
									jls = manualJobList;
								}
								function res(idList) {
									return jls.reduce((total, item) => {
										if (idList.indexOf(item.value) > -1) {
											total.push(item.label);
										}
										return total;
									}, []);
								}
								return ids.length > 5 ? (
									<div>
										{res(ids.slice(0, 5)).map((i, k) => {
											return (
												<div className="df aic">
													{i}
													{k === 4 && (
														<>
															<div>等{ids.length}个资产地址</div>
															<EyesTip
																data={res(ids).map(i => {
																	return <div>{i}</div>;
																})}
															/>
														</>
													)}
												</div>
											);
										})}
									</div>
								) : (
									res(ids).map(i => {
										return <div>{i}</div>;
									})
								);
							})()}
						</div>
					</div>
					<div className={cn(s.df, s.aic, s.bd)}>
						<div className={cn(s.p10_20)}>任务类型</div>
						<div className={cn(s.p10_20, s.bdl, s.flex1)}>
							{formData?.trigger_type === 'schedule' ? '周期性' : '单次'}任务
						</div>
					</div>
					{is_support ? (
						<div className={cn(s.df, s.aic, s.bd)}>
							<div className={cn(s.p10_20)}>
								{formData?.trigger_type === 'schedule'
									? '监测时间段'
									: '执行方式'}
							</div>
							<div className={cn(s.p10_20, s.bdl, s.flex1)}>
								{formData?.trigger_type === 'schedule'
									? formData?.ws_task_time?.periodStartTime &&
									  formData?.ws_task_time?.periodEndTime
										? `${moment(formData?.ws_task_time?.periodStartTime).format(
												'HH:mm'
										  )} - ${moment(
												formData?.ws_task_time?.periodEndTime
										  ).format('HH:mm')}`
										: '- -'
									: formData?.ws_task_time?.startType === 'now'
									? '立即执行'
									: `定时执行：${moment(formData?.ws_task_time?.startAt).format(
											'YYYY-MM-DD HH:mm:ss'
									  )}`}
							</div>
						</div>
					) : (
						''
					)}
					{(formData?.hostSettings?.is_detect_os_enabled ||
						formData?.hostSettings?.is_tcp_enabled ||
						formData?.hostSettings?.is_udp_enabled) && (
						<div className={cn(s.df, s.aic, s.bd)}>
							<div className={cn(s.p10_20)}>主机安全</div>
							<div className={cn(s.p10_20, s.bdl, s.flex1)}>
								{formData?.trigger_type === 'schedule' && (
									<div className={s.mb10}>
										监测频率：
										{intervalFormat(formData?.interval)}1次
									</div>
								)}
								<div className={s.mb10}>
									操作系统识别：
									{formData?.hostSettings?.is_detect_os_enabled
										? '开启'
										: '关闭'}
								</div>
								<div className={s.mb10}>
									监测内容：
									{['漏洞模版-服务弱口令', '数据库漏洞', '中间件漏洞'].map(
										(item, index) => {
											return (
												<span key={item}>
													{index ===
													['漏洞模版-服务弱口令', '数据库漏洞', '中间件漏洞']
														.length -
														1
														? item
														: item + '、'}
												</span>
											);
										}
									)}
								</div>
								<div className={s.mb10}>
									监测端口： x.x.x.x、x.x.x.x等1000个常用端口
									{/* <Dropdown
										menu={{ mockItems }}
										placement="topRight"
										arrow={{ pointAtCenter: true }}
									> */}
									<EyeOutlined className={cn(s.icon)} />
									{/* </Dropdown>  */}
								</div>
								<div className="df aic">
									<div className="flex1">
										扫描TCP端口：
										{formData?.hostSettings?.is_tcp_enabled ? '开启' : '关闭'}
									</div>
									<div className="flex1">
										扫描UDP端口：
										{formData?.hostSettings?.is_udp_enabled ? '开启' : '关闭'}
									</div>
								</div>
							</div>
						</div>
					)}
				</div>
				{atid && (
					<div className="warning-color pl20">
						您修改的配置将在下一周期生效。
					</div>
				)}
			</Dialog>
		</div>
	);
}
export default CreateJobAll;
